#include "login.h"
#include "widget.h"
#include "ui_login.h"
#include <QDebug>
#include <QTcpSocket>
#include <QTimer>
#include "LabelUtils.h"
Login::Login(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Login)
{
    ui->setupUi(this);

    // 初始化 TCP 客户端
    tcpSocket = new QTcpSocket(this);
    connect(tcpSocket, &QTcpSocket::connected, this, &Login::onConnected);
    connect(tcpSocket, &QTcpSocket::readyRead, this, &Login::onReadyRead);
    connect(tcpSocket, &QTcpSocket::errorOccurred, this, &Login::onErrorOccurred);

    // 连接到服务器
    tcpSocket->connectToHost("47.96.159.221", 7562);

    // 如果连接失败，尝试重新连接
    QTimer::singleShot(5000, this, [&]() {
        if (!tcpSocket->isValid() || tcpSocket->state() != QAbstractSocket::ConnectedState) {
            qDebug() << "连接失败，尝试重新连接...";
            ui->tishi->setText("未连接到服务器");
              LabelUtils::setLabelColor( ui->tishi, QColor("red"));  // 设置文本颜色为红色
            tcpSocket->connectToHost("47.96.159.221", 7562);
        }
    });

    connect(ui->loginBtn, &QPushButton::clicked, this, &Login::click_LoginBtn);
}

Login::~Login()
{
    delete ui;
    tcpSocket->disconnectFromHost();
    tcpSocket->deleteLater();
}

void Login::click_LoginBtn()
{
    QString username = ui->nameInput->text();
    if (username.isEmpty()) {
        qDebug() << "用户名不能为空";
        ui->tishi->setText("用户名不能为空");
        LabelUtils::setLabelColor( ui->tishi, QColor("red"));  // 设置文本颜色为红色
        return;
    }

    // 发送用户名到服务器
    tcpSocket->write(username.toUtf8());
    tcpSocket->flush();
}

void Login::onConnected()
{
    qDebug() << "连接到服务器成功";
    ui->tishi->setText("服务器连接成功");
}

void Login::onReadyRead()
{
    qDebug() << "Login::onReadyRead 被调用";
    QByteArray data = tcpSocket->readAll();
    QString response = QString::fromUtf8(data);

    qDebug() << "服务器响应：" << response;

    if (response.startsWith("用户名注册成功")) {
        qDebug() << "注册成功，跳转到主窗口";
        disconnect(tcpSocket, &QTcpSocket::readyRead, this, &Login::onReadyRead);
        this->close();  // 关闭当前登录窗口

        Widget *w = new Widget(nullptr);  // 创建新的窗口
        w->setTcpSocket(tcpSocket,ui->nameInput->text());  // 将 tcpSocket 传递给主窗口
        w->setWindowTitle("欢迎使用");
        w->show();  // 显示新窗口
    } else if (response.startsWith("用户名已存在")) {
        qDebug() << "注册失败，用户名已存在";
        // 可以在这里弹出提示框，提示用户用户名已存在
        ui->tishi->setText("该用户名已被登录");
        LabelUtils::setLabelColor( ui->tishi, QColor("red"));  // 设置文本颜色为红色
    } else {
        qDebug() << "未知响应：" << response;
    }
}



void Login::onErrorOccurred(QAbstractSocket::SocketError socketError)
{
    qDebug() << "TCP 错误：" << socketError;
}
